<?
/**
 * VoiceOne Webservices Methods
 * 
 * @package voiceone_webservices
 * @subpackage Contacts
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
function getContact($id,$id_user){
  global $db;
  //set where string
  $where="";
  if((isset($id))&&($id!="")&&($id!=0)) $where="WHERE `id`='".$id."'";
  else if((isset($id_user))&&($id_user!="")&&($id_user!=0)){
    //retireve user type
    $userArr=getUser($id_user);
    if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
      $where="WHERE (`id_user`='".$id_user."' OR `read`='1') ";
    }
  }
  //get contacts
  $qry="SELECT * FROM `cw_contacts` ".$where." ORDER BY order_field ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=id;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    //get copntact's gropus
    $contact['groups']=getContactGroup(0,$id_user);
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
function putContact($contact,$id_user){
  global $db;
  //set update if provisioning client already exists
  if((isset($contact["id"]))&&($contact["id"]!="")&&($contact["id"]!=0)){
    $id=$contact["id"];
    delContact($id,$id_user);
  }else{
    $id="null";
  }
  //reset cid setting for phonenumber and mobile number
  if(($contact["phonenumber_on_cid"]==1)&&(trim($contact["phonenumber"])!="")){
    $qry="UPDATE `cw_contacts` SET `phonenumber_on_cid`=0 WHERE `phonenumber` LIKE '".$contact["phonenumber"]."'";
    $res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `mobile_on_cid`=0 WHERE `mobile` LIKE '".$contact["phonenumber"]."'";
    $res=$db->Execute($qry);
  }
  if(($contact["mobile_on_cid"]==1)&&(trim($contact["mobile"])!="")){
  	$qry="UPDATE `cw_contacts` SET `mobile_on_cid`=0 WHERE `mobile` LIKE '".$contact["mobile"]."'";
  	$res=$db->Execute($qry);
    $qry="UPDATE `cw_contacts` SET `phonenumber_on_cid`=0 WHERE `phonenumber` LIKE '".$contact["mobile"]."'";
  	$res=$db->Execute($qry);
  }
  //create order field
  $order_field="";
  if($contact["order_by"]=="name"){
  	$order_field=trim($contact["name"]).trim($contact["surname"]).trim($contact["company"]);
  	if(trim($contact["cid_name"])==""){
    	if((trim($contact["company"])=="")&&(trim($contact["surname"])=="")){
      	$contact["cid_name"]=substr(trim($contact["name"]),0,254);
     	}else if(trim($contact["company"])==""){
     		$contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"]),0,254);
      }else if(trim($contact["surname"])==""){
				$contact["cid_name"]=substr(trim($contact["name"])." (".trim($contact["company"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"])." (".trim($contact["company"]).")",0,254);
      }
 			/*
    	if(trim($contact["company"])!="") $contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"])." (".trim($contact["company"]).")",0,254);
      else $contact["cid_name"]=substr(trim($contact["name"])." ".trim($contact["surname"]),0,254);
      */
    }  
  }else if($contact["order_by"]=="company"){
  	$order_field=trim($contact["company"]).trim($contact["surname"]).trim($contact["name"]);
  	if(trim($contact["cid_name"])==""){
     	if((trim($contact["name"])=="")&&(trim($contact["surname"])=="")){
      	$contact["cid_name"]=substr(trim($contact["company"]),0,254);
     	}else if(trim($contact["name"])==""){
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["surname"]).")",0,254);
      }else if(trim($contact["surname"])==""){
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["name"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["company"])." (".trim($contact["surname"])." ".trim($contact["name"]).")",0,254);
      }
    }
  }else{
  	$order_field=trim($contact["surname"]).trim($contact["name"]).trim($contact["company"]);
    if(trim($contact["cid_name"])==""){
    	if((trim($contact["company"])=="")&&(trim($contact["name"])=="")){
      	$contact["cid_name"]=substr(trim($contact["surname"]),0,254);
     	}else if(trim($contact["company"])==""){
     		$contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"]),0,254);
      }else if(trim($contact["name"])==""){
				$contact["cid_name"]=substr(trim($contact["surname"])." (".trim($contact["company"]).")",0,254);
      }else{
     		$contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"])." (".trim($contact["company"]).")",0,254);
      }
    	/*
    	if(trim($contact["company"])!="") $contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"])." (".trim($contact["company"]).")",0,254);
      else $contact["cid_name"]=substr(trim($contact["surname"])." ".trim($contact["name"]),0,254);
      */
    }
  }
  //insert provisioning client
  $qry="INSERT INTO `cw_contacts`(`id`,`id_user`,`read`,`write`,`name`,`surname`,`company`,`phonenumber`,`mobile`,`email`,`app_phonenumber`,`app_mobile`,`phonenumber_on_cid`,`mobile_on_cid`,`order_by`,`order_field`,`cid_name`) ";
  $qry.="VALUES (".$id.",'".string2sql($contact["id_user"])."','".string2sql($contact["read"])."','".string2sql($contact["write"])."','".string2sql($contact["name"])."','".string2sql($contact["surname"])."',";
  $qry.="'".string2sql($contact["company"])."','".string2sql($contact["phonenumber"])."','".string2sql($contact["mobile"])."','".string2sql($contact["email"])."','".string2sql($contact["phonenumber_speed_id"])."',";
  $qry.="'".string2sql($contact["mobile_speed_id"])."','".string2sql($contact["phonenumber_on_cid"])."','".string2sql($contact["mobile_on_cid"])."','".string2sql($contact["order_by"])."','".string2sql(strtolower($order_field))."','".string2sql($contact["cid_name"])."'); ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  if($id=="null") $id=$db->Insert_ID();
  //insert contact in groups
  delContactFromGroup($id,0);
  if(trim($contact["groups"])!=""){
    $groupArr=explode("|",$contact["groups"]);
    if(is_array($groupArr)){
      foreach($groupArr as $group){ 
        putContactInGroup($id,$group);
      }
    }
  }
  //create application for speeddials
  $ret=getMacroByName("reroute");
  if((is_array($ret))&&(is_array($ret[0]))){
  	$macro=$ret[0]["id"];
    //create application for phonenumber
    if((trim($contact["phonenumber_speed_ext"])!="")&&(trim($contact["phonenumber"])!="")){
    	//put application
    	if((trim($contact["phonenumber_speed_id"])!="")&&(trim($contact["phonenumber_speed_id"])!=0)){
      	$speed_id=trim($contact["phonenumber_speed_id"]);
      }else $speed_id="";
    	$speed_ext=trim($contact["phonenumber_speed_ext"]);
      $speed_num=$contact["phonenumber"];
      $speed_name="speed_".trim($id)."_phone";
      $entry=array(
          'id'          => $speed_id,
          'name'        => $speed_name,
          'label'       => "Speed_".trim($id)."_phone",
          'description' => "Speed dial for contact ".$contact["surname"]." ".$contact["name"]." (".$contact["company"].") on phonenumber ".$speed_num,
          'extension'   => $speed_ext,
          'code'        => "",
          'macro'       => $macro,
          'parameter'   => "destination=".$speed_num."|rule=",
          'groups'      => array()
      	);
      putApplication($entry);
      //get application id and update contact
      $ret=getApplicationByName($speed_name);
      if((is_array($ret))&&(is_array($ret[0]))){
  			$app_phonenumber=trim($ret[0]["id"]);
        if(($app_phonenumber!=0)&&($app_phonenumber!="")){
        	$qry="UPDATE `cw_contacts` SET `app_phonenumber`='".$app_phonenumber."' WHERE id='".$id."' ";
          $res=$db->Execute($qry);
  				if($res===false) return 0;
        }
      }
    }
    //create application for mobile
    if((trim($contact["mobile_speed_ext"])!="")&&(trim($contact["mobile"])!="")){
    	//put application
    	if((trim($contact["mobile_speed_id"])!="")&&(trim($contact["mobile_speed_id"])!=0)){
      	$speed_id=trim($contact["mobile_speed_id"]);
      }else $speed_id="";
    	$speed_ext=trim($contact["mobile_speed_ext"]);
      $speed_num=$contact["mobile"];
      $speed_name="speed_".trim($id)."_mobile";
      $entry=array(
          'id'          => $speed_id,
          'name'        => $speed_name,
          'label'       => "Speed_".trim($id)."_mobile",
          'description' => "Speed dial for contact ".$contact["surname"]." ".$contact["name"]." (".$contact["company"].") on mobile ".$speed_num,
          'extension'   => $speed_ext,
          'code'        => "",
          'macro'       => $macro,
          'parameter'   => "destination=".$speed_num."|rule=",
          'groups'      => array()
      	);
      putApplication($entry);
      //get application id and update contact
      $ret=getApplicationByName($speed_name);
      if((is_array($ret))&&(is_array($ret[0]))){
  			$app_mobile=trim($ret[0]["id"]);
        if(($app_mobile!=0)&&($app_mobile!="")){
        	$qry="UPDATE `cw_contacts` SET `app_mobile`='".$app_mobile."' WHERE id='".$id."' ";
          $res=$db->Execute($qry);
  				if($res===false) return 0;
        }
      }
    }
  }else return 0;
  //return
	return 1;
}
function delContact($id,$id_user){
  global $db;
  //Checks
  if((!isset($id))||($id=="")||($id==0)) return 0;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  //get contact info
  $app_phonenumber=0;
  $app_mobile=0;
  $contact=getContact($id,$id_user);
  if((is_array($contact))&&(is_array($contact[0]))){
  	$app_phonenumber=$contact[0]['phonenumber_speed_id'];
    $app_mobile=$contact[0]['mobile_speed_id'];
  }
  //delete contact
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]!=USER_STANDARD)){
    $where="WHERE `id`=".$id."";
  }else{
    $where="WHERE `id`=".$id." AND (`id_user`='".$id_user."' OR `write`='1')";
  }
  $qry="DELETE FROM `cw_contacts` ".$where." LIMIT 1";
  $res=$db->Execute($qry);
  if($res===false) return 0; 
  //delete applications
  $q=$db->Affected_Rows();
  if($q==1){
  	if($app_phonenumber!=0) delApplication($app_phonenumber);
  	if($app_mobile!=0) delApplication($app_mobile);
  }
  //return
  return 1;
}
function getContactIndex($id_user,$search){
  global $db;
	//retireve user type and set where string
  $where="";
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
    $where="WHERE (`id_user`='".$id_user."' OR `read`='1') ";
  }else $where="WHERE 1 ";
  //process filter
  $and_filter="";
  if(trim($search)!=""){
  	$searchArr=split(" ",$search);
    if(is_array($searchArr)){
      foreach($searchArr as $s){
      	$s=string2sql($s);
      	$and_filter.="AND ( ";
        $and_filter.="LOWER(`name`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`surname`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`company`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`phonenumber`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`mobile`) LIKE '%".strtolower($s)."%' ";
       	$and_filter.=") ";
      }
    }
  }
  //get Contacts
  $qry="SELECT LOWER(SUBSTRING(`order_field`,1,1)) as `character`,COUNT(*) as `number` ";
  $qry.="FROM `cw_contacts` ";
  $qry.="".$where." ";
  $qry.="".$and_filter."";
  $qry.="GROUP BY LOWER(SUBSTRING(`order_field`,1,1)) ";
  $qry.="ORDER BY LOWER(SUBSTRING(`order_field`,1,1)) ASC"; 
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	$ret[]=array("key"=>$arr["character"],"value"=>$arr["number"]);
  }
  //return
  return $ret;
}
function getContactList($id_user,$starting,$search,$res_num,$page){
  global $db;
	//retireve user type and set where string
  $where="";
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]==USER_STANDARD)){
    $where="WHERE (`id_user`='".$id_user."' OR `read`='1') ";
  }else $where="WHERE 1 ";
  //process filter
  $and_filter="";
  if(trim($search)!=""){
  	$searchArr=split(" ",$search);
    if(is_array($searchArr)){
      foreach($searchArr as $s){
      	$s=string2sql($s);
      	$and_filter.="AND ( ";
        $and_filter.="LOWER(`name`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`surname`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`company`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`phonenumber`) LIKE '%".strtolower($s)."%' OR ";
        $and_filter.="LOWER(`mobile`) LIKE '%".strtolower($s)."%' ";
       	$and_filter.=") ";
      }
    }
  }
  //process limit
  if($res_num!=0){
  	if(($page==0)||($page==1)) $limit="LIMIT 0 , ".intval($res_num)." ";
    else $limit="LIMIT ".intval(($page-1)*$res_num)." , ".intval($res_num)." ";
  }
  //process char
  if(trim($starting)!="") $and_char="AND LOWER(SUBSTRING(`order_field`,1,1))='".string2sql(strtolower(substr($starting,0,1)))."' ";
  else $and_char="";
  //get contacts
  $qry="SELECT `id`,`name`,`surname`,`company`,`order_by`,`id_user`,`write`,`phonenumber`,`mobile` ";
  $qry.="FROM `cw_contacts` ";
  $qry.="".$where."";
  $qry.="".$and_filter."";
  $qry.="".$and_char."";
  $qry.="ORDER BY `order_field` "; 
  $qry.="".$limit."";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    if($arr["order_by"]=="name"){
    	if(trim($arr["company"])!="") $name=$arr["name"]." ".$arr["surname"]." (".$arr["company"].")";
      else $name=$arr["name"]." ".$arr["surname"];
    }else if($arr["order_by"]=="company"){
    	if((trim($arr["surname"])!="")||(trim($arr["name"])!="")) $name=$arr["company"]." (".$arr["surname"]." ".$arr["name"].")";
      else $name=$arr["company"];
    }else{
    	if(trim($arr["company"])!="") $name=$arr["surname"]." ".$arr["name"]." (".$arr["company"].")";
      else $name=$arr["surname"]." ".$arr["name"];
    }
  	$ret[]=array(
    		"id"=>$arr["id"],
        "id_user"=>$arr["id_user"],
        "name"=>$name,
        "write"=>$arr["write"],
        "phonenumber"=>$arr["phonenumber"],
        "mobile"=>$arr["mobile"]
      );
  }
  //return
  return $ret;
}
function getContactFromPhonenumber($phonenumber){
  global $db;
  //set where string
  $where="";
  if((!isset($phonenumber))||(trim($phonenumber)=="")) return 0;
  //get contacts
  $qry="SELECT * FROM `cw_contacts` WHERE `phonenumber` LIKE '".$phonenumber."' ORDER BY `phonenumber_on_cid` DESC";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=id;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
function getContactFromMobile($mobile){
  global $db;
  //set where string
  $where="";
  if((!isset($mobile))||(trim($mobile)=="")) return 0;
  //get contacts
  $qry="SELECT * FROM `cw_contacts` WHERE `mobile` LIKE '".$mobile."' ORDER BY `mobile_on_cid` DESC";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
  	//get general settings
    $contact=array(
    	'id'            => $arr["id"],
      'id_user'       => $arr["id_user"],
      'name'          => $arr["name"],
      'surname'       => $arr["surname"],
      'company'       => $arr["company"],
      'email'         => $arr["email"],
      'read'          => $arr["read"],
      'write'         => $arr["write"],
      'phonenumber'   => $arr["phonenumber"],
      'mobile'        => $arr["mobile"],
      'phonenumber_on_cid' 	=> $arr["phonenumber_on_cid"],
      'mobile_on_cid'    		=> $arr["mobile_on_cid"],
      'order_by' 						=> $arr["order_by"],
      'cid_name' 						=> $arr["cid_name"]
    );
    //get application settings
    if(($arr['app_phonenumber']!=0)&&(trim($arr['app_phonenumber'])!="")){
    	$app=getApplication($arr['app_phonenumber']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['phonenumber_speed_id']=$app[0]["id"];
        $contact['phonenumber_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['phonenumber_speed_id']=id;
        $contact['phonenumber_speed_ext']="";
      }
    }else{
    	$contact['phonenumber_speed_id']=0;
      $contact['phonenumber_speed_ext']="";
    }
	  if(($arr['app_mobile']!=0)&&(trim($arr['app_mobile'])!="")){
    	$app=getApplication($arr['app_mobile']);
      if((is_array($app))&&(is_array($app[0]))){
     		$contact['mobile_speed_id']=$app[0]["id"];
        $contact['mobile_speed_ext']=$app[0]["extension"];
      }else{
      	$contact['mobile_speed_id']=0;
        $contact['mobile_speed_ext']="";
      }
    }else{
    	$contact['mobile_speed_id']=0;
      $contact['mobile_speed_ext']="";
    }
    //save in array
    $ret[]=$contact;
  }
  //return
  return $ret;
}
//******************           Groups of Contacts            *******************
function getContactGroup($id,$id_user){
  global $db;
  if((!isset($id_user))&&($id_user=="")&&($id_user==0)) return 0;
  //set where string
  $where="";
  if((isset($id))&&($id!="")&&($id!=0)) $where="WHERE `id`='".$id."'";
  //get groups of contacts
  $qry="SELECT * FROM `cw_contacts_group` ".$where." ORDER BY `name` ";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  while($arr=$res->FetchRow()){
    $entity=array();
    //get entities
    $qry="SELECT id_contact ";
    $qry.="FROM `cw_contacts_group_entity` AS ge ";
    $qry.="JOIN `cw_contacts` AS c ON c.`id` = ge.`id_contact` ";
    $qry.="WHERE ge.`id_group`='".$arr["id"]."' ";
    $userArr=getUser($id_user);
    if((!is_array($userArr))||($userArr[0]["type"]==USER_STANDARD)){
      $qry.="AND (`id_user`='".$id_user."' OR `read`='1')";
    }
    $res2=$db->Execute($qry);
    if($res2===false) return 0;
    while($c=$res2->FetchRow()) $entity[]=$c["id_contact"];
    $arr["entity"]=$entity;
    $ret[]=$arr;
  }
  //return
  return $ret;
}
function putContactGroup($contactGroup,$id_user){
  global $db;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  //set update if provisioning client already exists
  if((isset($contactGroup["id"]))&&($contactGroup["id"]!="")&&($contactGroup["id"]!=0)){
    $id=$contactGroup["id"];
    delContactGroup($id,$id_user,true);
  }else{
    $id="null";
  }
  //insert provisioning client
  $qry="INSERT INTO `cw_contacts_group`(`id`,`name`) ";
  $qry.="VALUES (".$id.",'".string2sql($contactGroup["name"])."'); ";
  $res=$db->Execute($qry);
  //link contact entities
  if($res===false) return 0;
  else{
    if($id=="null") $id=$db->Insert_ID();
    //insert entities
    if(is_array($contactGroup["entity"])){
      foreach($contactGroup["entity"] as $entity){
        $qry="INSERT INTO `cw_contacts_group_entity`(`id_group`,`id_contact`) ";
        $qry.="VALUES (".$id.",'".$entity."'); ";
        $res=$db->Execute($qry);
        if($res===false) return 0;
      }
    }
  }
  //return
  return 1;
}
function delContactGroup($id,$id_user,$modify=false){
  global $db;
  if((!isset($id_user))||($id_user=="")||($id_user==0)) return 0;
  if((!isset($id))||($id=="")||($id==0)) return 0;
  //Delete permanently
  if($modify===false){
    if(isContactGroupErasable($id,$id_user)!=1) return 0;
    else{
      $qry="DELETE FROM `cw_contacts_group` WHERE `id`=".$id." LIMIT 1";
      $res=$db->Execute($qry);
      if($res===false) return 0; 
      $qry="DELETE FROM `cw_contacts_group_entity` WHERE `id_group`='".$id."' ";
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }
  }
  //Delete before reinsert
  else{
    $qry="DELETE FROM `cw_contacts_group` WHERE `id`=".$id." LIMIT 1";
    $res=$db->Execute($qry);
    if($res!==false){
      //delete group entities related to the user
      $qry="DELETE FROM `cw_contacts_group_entity` ";
      $qry.="WHERE `id_group`='".$id."' ";
      $userArr=getUser($id_user);
      if((!is_array($userArr))||($userArr[0]["type"]==USER_STANDARD)){
        $qry.="AND `id_contact` IN ( ";
        $qry.="SELECT `id` FROM `cw_contacts` "; 
        $qry.="WHERE ( `id_user`='".$id_user."' OR `write`='1' ) ";
        $qry.=")"; 
      }
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }else return 0;
  }
  //return
  return 1;
}
function isContactGroupErasable($id,$id_user){
  global $db;
  $userArr=getUser($id_user);
  if((is_array($userArr))&&($userArr[0]["type"]!=USER_STANDARD)) return 1;
  else{
    $qry="SELECT id_contact ";
    $qry.="FROM `cw_contacts_group_entity` AS ge ";
    $qry.="JOIN `cw_contacts` AS c ON c.`id` = ge.`id_contact` ";
    $qry.="WHERE ge.`id_group`='".$id."' ";
    $qry.="AND (c.`id_user`<>'".$id_user."' AND c.`write`='0')";
    $res=$db->Execute($qry);
    $q=$res->RecordCount();
    if($q==0) return 1;
  }
  //return
  return 0;
}
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
function putContactInGroup($id_contact,$id_group){
  global $db;
  if((!isset($id_contact))||($id_contact=="")||($id_contact==0)) return 0;
  if((!isset($id_group))||($id_group=="")||($id_group==0)) return 0;
  //verify if contact is already in group
  $qry="SELECT * FROM `cw_contacts_group_entity` WHERE `id_contact`='".$id_contact."' AND `id_group`='".$id_group."' ";
  $res=$db->Execute($qry);
  if($res!==false){
    $q=$res->RecordCount();
    if($q==0){
      $qry="INSERT INTO `cw_contacts_group_entity`(`id_group`,`id_contact`) ";
      $qry.="VALUES ('".$id_group."','".$id_contact."') ";
      $res=$db->Execute($qry);
      if($res===false) return 0;
    }
  }
  //return
  return 1;
}
function delContactFromGroup($id_contact,$id_group){
  global $db;
  if((!isset($id_contact))||($id_contact=="")||($id_contact==0)) return 0;
  if((!isset($id_group))||($id_group=="")||($id_group==0)) $where_group="";
  else $where_group="AND `id_group`='".$id_group."'";
  //verify if contact is already in group
  $qry="DELETE FROM `cw_contacts_group_entity` WHERE `id_contact`='".$id_contact."' ".$where_group." ";
  $res=$db->Execute($qry);
  if($res!==false) return 0;
  return 1;
}
?>